<?php
namespace models\service;
//use PEAR;

class BerkasService {

	protected $ci;
	public $lastBerkas;

	public function __construct() {
		$this -> ci = &get_instance();
	}

	public function paginateBerkas($indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> paginateBerkas($indexAndCount, $orders);
	}

	public function paginateBerkasByMap($map, $indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> paginateBerkasByMap($map, $indexAndCount, $orders);
	}
	
	public function paginateBerkasByMap2($map, $indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> paginateBerkasByMap2($map, $indexAndCount, $orders);
	}

	// Start Service for Jenis Data
	public function findAllPerpustakaan($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Perpustakaan') -> findAll($orderBy);
	}

	// End Service for Jenis Data

	// Start Service for Indicator
	public function findAllIndicator($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Indicator') -> findAll($orderBy);
	}

	// End Service for Indicator

	// Start Service for TipeBerkas
	public function findAllTipeBerkas($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\TipeBerkas') -> findAll($orderBy);
	}

	// Start Service for Quarter
	public function findAllQuarter($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Quarter') -> findAll($orderBy);
	}

	// End Service for Quarter

	// Start Service for Distrik
	public function findAllDistrik($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Distrik') -> findAll($orderBy);
	}

	public function findAllDesa($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Desa') -> findAll($orderBy);
	}

	// End Service for Distrik

	// Start Service for Sector
	public function findAllSector($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Sector') -> findAll($orderBy);
	}

	// End Service for Sector

	// Start Service for Package
	public function findAllPackage($orderBy = null) {
		return $this -> ci -> em -> getRepository('\models\entities\Package') -> findAll($orderBy);
	}

	// End Service for Package

	public function paginateBarangItemByMap($map, $indexAndCount, $orders) {
		return $this -> ci -> em -> getRepository('\models\entities\BarangItem') -> paginateByMap($map, $indexAndCount, $orders);
	}

	public function getBerkasById($isLazzy = FALSE, $id) {
		$criteria = array('id' => $id);
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findByOne(TRUE, $criteria);
	}

	public function getBerkasTotalByType($status) {
		return $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findNumberBerkasByType($status);
	}
	
	/**
	 *
	 */
	public function save($param) {
		if ($param['Berkas']['id'] != "0") {
			$criteria = array('id' => $param['Berkas']['id']);
			$berkas = $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findOneBy($criteria);
			//$berkas->setEventDate($now);
		} else {
			$berkas = new \models\entities\Berkas;
			$noUrut = $this -> generateNewBerkasCode($param['Berkas']['tipe']);
			$berkas -> setId($noUrut);
		}

		if (key_exists('description', $param['Berkas']) && $param['Berkas']['description'] != "") {
			$berkas -> setDescription($param['Berkas']['description']);
		}

		if (key_exists('hasilKegiatan', $param['Berkas']) && $param['Berkas']['hasilKegiatan'] != "") {
			$berkas -> setHasilKegiatan($param['Berkas']['hasilKegiatan']);
		}

		if (key_exists('tantangan', $param['Berkas']) && $param['Berkas']['tantangan'] != "") {
			$berkas -> setTantangan($param['Berkas']['tantangan']);
		}

		/*
		 if (key_exists('eventDate', $param['Berkas']) && $param['Berkas']['eventDate'] != ""){
		 $reportDate = new \DateTime($param['Berkas']['eventDate'], new \DateTimeZone("Asia/Jakarta"));
		 $berkas->setEventDate($reportDate);
		 }		*/

		if (key_exists('perpustakaan', $param['Berkas']) && $param['Berkas']['perpustakaan'] != "") {
			$criteria = array('id' => $param['Berkas']['perpustakaan']);
			$perpustakaan = $this -> ci -> em -> getRepository('\models\entities\Perpustakaan') -> findOneBy($criteria);
			$berkas -> setPerpustakaan($perpustakaan);
		} else {
			throw new \Exception("TIDAK ADA DATA PERPUSTAKAAN");
		}

		if (key_exists('tipe', $param['Berkas']) && $param['Berkas']['tipe'] != "") {
			$criteria = array('id' => $param['Berkas']['tipe']);
			$tipe = $this -> ci -> em -> getRepository('\models\entities\TipeBerkas') -> findOneBy($criteria);
			$berkas -> setTipe($tipe);
		}

		if (key_exists('reporter', $param['Berkas']) && $param['Berkas']['reporter'] != "") {
			$berkas -> setReporter($param['Berkas']['reporter']);
		}

		try {
			$this -> ci -> em -> persist($berkas);
			$this -> ci -> em -> flush();
			//print_r($berkas);die();
			return $berkas;
		} catch (\Exception $e) {

			return FALSE;
		}
	}

	public function generateNewBerkasCode($tipeBerkasId) {
		$criteria = array('id' => $tipeBerkasId);
		$tipeBerkas = $this -> ci -> em -> getRepository('\models\entities\TipeBerkas') -> findOneBy($criteria);
		$prefiks = $tipeBerkas -> getPrefiksCode();
		$bulan = date('m');
		$code = $prefiks . $bulan;
		//die($code);
		//echo $code;
		$noUrut = $this -> ci -> em -> getRepository('\models\entities\Berkas') -> findNoUrut($code);
		if ($noUrut == NULL) {
			$code .= "0001";
		} else {
			$noUrut = $noUrut + 1;
			$code .= sprintf('%04d', $noUrut);
		}
		//die($code);
		return $code;
	}

	public function saveBerkasAsDraft($param) {
		if ($param != null) {
			//echo "<pre>"; print_r($berkas);die();
			$this -> ci -> em -> getConnection() -> beginTransaction();
			// suspend auto-commit
			try {
				$berkas = $this -> save($param);
				if ($berkas === FALSE) {
					throw new \Exception("GAGAL SAVE BERKAS");
				}
				if ($param['Berkas']['id'] == '0') {
					if ($this -> saveBerkasIndicator($berkas, $param) === FALSE) {
						throw new \Exception("GAGAL INSERT BERKASINDICATOR");
					}

					if ($berkas -> getTipe() -> getId() == "TRAINING") {
						if ($this -> insertParticipantOfTraining($berkas, $param) === FALSE) {
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");
						}
					}

					$inboxService = new InboxService;
					$criteria = array('id' => $param['Profile']['id']);
					$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
					if ($inboxService -> startNewFlow($berkas, $profile) === FALSE) {
						throw new \Exception("GAGAL START NEW FLOW");
					}
				} else {
					if ($this -> saveBerkasIndicator($berkas, $param) === FALSE) {
						throw new \Exception("GAGAL SAVE BERKASINDICATOR");
					}

					if ($berkas -> getTipe() -> getId() == "TRAINING") {
						$criteria = array('berkas' => $berkas);
						$members = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy($criteria);
						if (count($members) > 0) {
							foreach ($members as $member) {
								$this -> deleteMemberOfTraining($member -> getId());
							}
						}
						if ($this -> insertParticipantOfTraining($berkas, $param) === FALSE) {
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");
						}
					}
				}

				if ($this -> saveBerkasKontribusi($berkas, $param) === FALSE) {
					throw new \Exception("GAGAL INSERT BERKASKONTRIBUSI");
				}
				//if ($this->isNewUploadFile($_FILES) === TRUE){
				$criteria = array('berkas' => $berkas);
				$berkasAttachments = $this -> ci -> em -> getRepository('\models\entities\BerkasAttachment') -> findBy($criteria);
				if (count($berkasAttachments) > 0) {
					$c = 1;
					foreach ($berkasAttachments as $berkasAttachment) {
						$index = 'attach' . $c;
						if ($_FILES[$index]['error'] == 0) {
							$this -> deleteBerkasAttachment($berkasAttachment -> getId());
						}
						$c++;
					}
					if ($this -> insertBerkasAttachment($berkas, $_FILES) === FALSE) {
						
						throw new \Exception("GAGAL UPLOAD DOC");
					}
				} else {
					if ($this -> insertBerkasAttachment($berkas, $_FILES) === FALSE) {
						throw new \Exception("GAGAL UPLOAD DOC");
					}
				}

				//throw new \Exception('berhasil');
				//}
				//echo "<pre>";print_r($_FILES);
				//throw new \Exception('coba');
				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				// echo $e -> getMessage();
				// die();
				//var_dump($e);
				return FALSE;
			}

			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function insertBerkasAttachment($berkas, $files) {
		// die($berkas->getId());
		$path = './attach/' . $berkas -> getId() . "/";

		if (!is_dir($path)) {
			mkdir($path, 0777, TRUE);
		}
		//echo "<pre>"; print_r($files);
		//die();

		if (array_key_exists('attach1', $_FILES) || array_key_exists('attach2', $_FILES) || array_key_exists('attach3', $_FILES) || array_key_exists('attach4', $_FILES) || array_key_exists('attach5', $_FILES)) {
			$i = 0;
			$config['upload_path'] = $path;
			$config['allowed_types'] = 'pdf|jpg|jpeg|png|doc|docx|xls|xlsx|ppt|pptx|zip|rar';
			$config['overwrite'] = true;
			foreach ($files as $key => $value) {
				$this -> ci -> load -> library('upload', $config);
				//$this->upload->initialize($config);
				if (!empty($value) && $files[$key]['error'] == 0) {
					if (!$this -> ci -> upload -> do_upload($key)) {
						$error = array('error' => $this -> ci -> upload -> display_errors());
						// FIX TO : send error notification
						$this->ci->session->set_userdata('flash_message',MESSAGE_REPORT_SENT_FAILED . ' Karena File Tidak Diperkenankan');
						return FALSE;
					} else {
						$data = array('upload_data' => $this -> ci -> upload -> data());
						$berkasAttachment = new \models\entities\BerkasAttachment;
						$berkasAttachment -> setBerkas($berkas);
						$berkasAttachment -> setStatus(1);
						$berkasAttachment -> setPath($path . $data['upload_data']['file_name']);
						$berkasAttachment -> setTypeFile($files[$key]['type']);
						try {
							$this -> ci -> em -> persist($berkasAttachment);
							$this -> ci -> em -> flush();

						} catch (Exception $e) {
							$this->session->set_userdata('flash_message',MESSAGE_REPORT_SENT_FAILED . $e->getMessage());
							return FALSE;
						}
					}
				}
			}
			return TRUE;

		}
	}

	public function saveBerkasIndicator($berkas, $param) {
		if ($berkas != NULL) {
			//echo $berkas->getId();
			if ($berkas -> getTipe() -> getId() == "TRAINING") {
				if ($param['Berkas']['id'] != '0') {
					$criteria = array('id' => $berkas);
					$berkasIndicator = $this -> ci -> em -> getRepository('\models\entities\BerkasTraining') -> findOneBy($criteria);
					if ($berkasIndicator == null){
						$berkasIndicator = new \models\entities\BerkasTraining;
						$berkasIndicator -> setId($berkas);
					}
				} else {
					$berkasIndicator = new \models\entities\BerkasTraining;
					$berkasIndicator -> setId($berkas);
				}
				//$berkasIndicator = new \models\entities\BerkasTraining;
				$criteria = array('id' => $param['BerkasTraining']['jenisTraining']);
				$jenisTraining = $this -> ci -> em -> getRepository('\models\entities\JenisTraining') -> findOneBy($criteria);
				$berkasIndicator -> setJenisTraining($jenisTraining);
				$berkasIndicator -> setJmlStaff($param['BerkasTraining']['jmlStaff']);
				$berkasIndicator -> setJmlNonStaff($param['BerkasTraining']['jmlNonStaff']);
				$berkasIndicator -> setJmlLainnya($param['BerkasTraining']['jmlLainnya']);
				$berkasIndicator -> setJmlPria($param['BerkasTraining']['jmlPria']);
				$berkasIndicator -> setJmlWanita($param['BerkasTraining']['jmlWanita']);
				if (key_exists('fromDate', $param['BerkasTraining']) && $param['BerkasTraining']['fromDate'] != "") {
					$fromDate = new \DateTime($param['BerkasTraining']['fromDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setFromDate($fromDate);
				}

				if (key_exists('toDate', $param['BerkasTraining']) && $param['BerkasTraining']['toDate'] != "") {
					$toDate = new \DateTime($param['BerkasTraining']['toDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setToDate($toDate);
				}
			} else if ($berkas -> getTipe() -> getId() == "LKPM") {
				if ($param['Berkas']['id'] != '0') {
					$criteria = array('id' => $berkas);
					$berkasIndicator = $this -> ci -> em -> getRepository('\models\entities\BerkasLkpm') -> findOneBy($criteria);
					if ($berkasIndicator == null){
						$berkasIndicator = new \models\entities\BerkasLkpm;
						$berkasIndicator -> setId($berkas);
					}					
				} else {
					$berkasIndicator = new \models\entities\BerkasLkpm;
					$berkasIndicator -> setId($berkas);
				}
				//$berkasIndicator = new \models\entities\BerkasTraining;
				$criteria = array('id' => $param['BerkasLkpm']['topikKegiatan']);
				$topikKegiatan = $this -> ci -> em -> getRepository('\models\entities\TopikKegiatan') -> findOneBy($criteria);
				$berkasIndicator -> setTopikKegiatan($topikKegiatan);
				//echo "<pre>";print_r($param);die();
				$criteria = array('id' => $param['BerkasLkpm']['jenisKegiatan']);
				$jenisKegiatan = $this -> ci -> em -> getRepository('\models\entities\JenisKegiatan') -> findOneBy($criteria);
				$berkasIndicator -> setJenisKegiatan($jenisKegiatan);
				$berkasIndicator -> setJumlahPria($param['BerkasLkpm']['jumlahPria']);
				$berkasIndicator -> setJumlahWanita($param['BerkasLkpm']['jumlahWanita']);
				$berkasIndicator -> setJumlahTotal($param['BerkasLkpm']['jumlahTotal']);

				if (key_exists('fromDate', $param['BerkasLkpm']) && $param['BerkasLkpm']['fromDate'] != "") {
					$fromDate = new \DateTime($param['BerkasLkpm']['fromDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setFromDate($fromDate);
				}

				if (key_exists('toDate', $param['BerkasLkpm']) && $param['BerkasLkpm']['toDate'] != "") {
					$toDate = new \DateTime($param['BerkasLkpm']['toDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setToDate($toDate);
				}

				if (key_exists('BerkasLkpmSasaran', $param) && count($param['BerkasLkpmSasaran']) > 0) {
					$criteria = array('berkas' => $berkas);
					$berkasLkpmSasarans = $this -> ci -> em -> getRepository('\models\entities\BerkasLkpmSasaran') -> findBy($criteria);
					try {
						if ($berkasLkpmSasarans > 0) {
							$i = 0;
							foreach ($berkasLkpmSasarans as $row) {
								$this -> ci -> em -> remove($row);
								//if (($i % $batchSize) === 0) {
								$this -> ci -> em -> flush();
									// Executes all deletions.
								//$this -> ci -> em -> clear();
									// Detaches all objects from Doctrine!
								//}
							}
							//$this -> ci -> em -> flush();
						}
						
						foreach ($param['BerkasLkpmSasaran'] as $row) {
							$berkasLkpmSasaran = new \models\entities\BerkasLkpmSasaran;
							$criteria = array('id' => $row);
							$sasaran = $this -> ci -> em -> getRepository('\models\entities\KelompokSasaran') -> findOneBy($criteria);
							$berkasLkpmSasaran -> setBerkas($berkas);
							$berkasLkpmSasaran -> setKelompokSasaran($sasaran);
							if ($param['kelompokNonPemerintah'] != ""){
								$berkasLkpmSasaran->setInstitusiLain($param['kelompokNonPemerintah']);
							}
							$this -> ci -> em -> persist($berkasLkpmSasaran);
							$this -> ci -> em -> flush();
						}
					} catch (Exception $e){
						echo $e -> getMessage();
						return FALSE;
					}
				}
			} else if ($berkas -> getTipe() -> getId() == "LAS") {
				if ($param['Berkas']['id'] != '0') {
					$criteria = array('id' => $berkas);
					$berkasIndicator = $this -> ci -> em -> getRepository('\models\entities\BerkasLas') -> findOneBy($criteria);
					if ($berkasIndicator == null){
						$berkasIndicator = new \models\entities\BerkasLas;
						$berkasIndicator -> setId($berkas);
					}
				} else {
					$berkasIndicator = new \models\entities\BerkasLas;
					$berkasIndicator -> setId($berkas);
				}
				
				$criteria = array('id' => $param['BerkasLas']['media']);
				$media = $this -> ci -> em -> getRepository('\models\entities\Media') -> findOneBy($criteria);
				$berkasIndicator -> setMedia($media);
				//echo "<pre>";print_r($param);die();
				$criteria = array('id' => $param['BerkasLas']['kategoriAsistensi']);
				$kategoriAsistensi = $this -> ci -> em -> getRepository('\models\entities\KategoriAsistensi') -> findOneBy($criteria);
				$berkasIndicator -> setKategoriAsistensi($kategoriAsistensi);
				
				$berkasIndicator -> setJenisAsistensi($param['BerkasLas']['jenisAsistensi']);
				
				if (key_exists('fromDate', $param['BerkasLas']) && $param['BerkasLas']['fromDate'] != "") {
					$fromDate = new \DateTime($param['BerkasLas']['fromDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setFromDate($fromDate);
				}

				if (key_exists('toDate', $param['BerkasLas']) && $param['BerkasLas']['toDate'] != "") {
					$toDate = new \DateTime($param['BerkasLas']['toDate'], new \DateTimeZone("Asia/Jakarta"));
					$berkasIndicator -> setToDate($toDate);
				}
				
			} else {
				return TRUE;
			}

			try {
				$this -> ci -> em -> persist($berkasIndicator);
				$this -> ci -> em -> flush();
				return TRUE;
			} catch (Exception $e) {
				echo $e -> getMessage();
				return FALSE;
			}

		} else {
			return FALSE;
		}
	}

	public function saveBerkasKontribusi($berkas, $param) {
		if ($berkas != NULL) {
			try {
				if (key_exists('BerkasKontribusi', $param) && count($param['BerkasKontribusi']) > 0) {
					$criteria = array('berkas' => $berkas);
					$berkasKontribusis = $this -> ci -> em -> getRepository('\models\entities\BerkasKontribusi') -> findBy($criteria);

					if (count($berkasKontribusis) > 0) {
						$i = 0;
						foreach ($berkasKontribusis as $row) {
							$this -> ci -> em -> remove($row);
							//if (($i % $batchSize) === 0) {
								$this -> ci -> em -> flush();
								// Executes all deletions.
							//	$this -> ci -> em -> clear();
								// Detaches all objects from Doctrine!
							//}
						}
						//$this -> ci -> em -> flush();
					}

					foreach ($param['BerkasKontribusi'] as $row) {
						$berkasKontribusi = new \models\entities\BerkasKontribusi;
						$criteria = array('id' => $row['kontribusi']);
						$kontribusi = $this -> ci -> em -> getRepository('\models\entities\Kontribusi') -> findOneBy($criteria);
						$berkasKontribusi -> setBerkas($berkas);
						$berkasKontribusi -> setKontribusi($kontribusi);
						$berkasKontribusi -> setJumlah($row['jumlah']);
						if ($kontribusi->getId() == 7){
							$berkasKontribusi->setNamaLain($row['namaLain']);
						}
						$this -> ci -> em -> persist($berkasKontribusi);
						$this -> ci -> em -> flush();
					}
					return TRUE;
				} else {
					return TRUE;
				}
			} catch (Exception $e) {
				return FALSE;
			}

		} else {
			return FALSE;
		}

	}

	public function insertParticipantOfTraining($berkas, $param) {
		if ($berkas != NULL) {
			if ($berkas -> getTipe() -> getId() == "TRAINING" && is_array($param['0'])) {
				foreach ($param['0']['MemberOfTraining'] as $row) {
					$participant = new \models\entities\ParticipantOfTraining;
					$participant -> setName($row['name']);
					$participant -> setGender($row['gender']);
					$participant -> setStaff($row['staff']);
					$participant -> setBerkas($berkas);
					try {
						$this -> ci -> em -> persist($participant);
						$this -> ci -> em -> flush();
						//return TRUE;
					} catch (Exception $e) {
						return FALSE;
					}
				}
				return TRUE;
			} else {
				return TRUE;
			}

		} else {
			return FALSE;
		}
	}

	public function saveAndSubmitBerkas($param) {

		if ($param != NULL) {
			$this -> ci -> em -> getConnection() -> beginTransaction();
			$user = \models\service\CurrentUser::user();
			// suspend auto-commit
			try {
				$berkas = $this -> save($param);
				if ($berkas === FALSE) {
					throw new \Exception("GAGAL SAVE BERKAS");
				}
				if ($param['Berkas']['id'] == '0') {
					if ($this -> saveBerkasIndicator($berkas, $param) === FALSE) {
						throw new \Exception("GAGAL INSERT BERKASINDICATOR");
					}

					if ($berkas -> getTipe() -> getId() == "TRAINING") {
						if ($this -> insertParticipantOfTraining($berkas, $param) === FALSE) {
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");
						}
					}

					$inboxService = new InboxService;
					$criteria = array('id' => $param['Profile']['id']);
					$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);
					if ($inboxService -> startNewFlow($berkas, $profile) === FALSE) {
						throw new \Exception("GAGAL START NEW FLOW");
					}
				} else {
					if ($this -> saveBerkasIndicator($berkas, $param) === FALSE) {
						throw new \Exception("GAGAL SAVE BERKASINDICATOR");
					}

					if ($berkas -> getTipe() -> getId() == "TRAINING") {
						$criteria = array('berkas' => $berkas);
						$members = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findBy($criteria);
						if (count($members) > 0) {
							foreach ($members as $member) {
								$this -> deleteMemberOfTraining($member -> getId());
							}
						}
						if ($this -> insertParticipantOfTraining($berkas, $param) === FALSE) {
							throw new \Exception("GAGAL INSERT MEMBEROFTRAINING");
						}
					}
				}

				if ($this -> saveBerkasKontribusi($berkas, $param) === FALSE) {
					throw new \Exception("GAGAL INSERT BERKASKONTRIBUSI");
				}

				$criteria = array('id' => $param['Profile']['id']);
				$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);

				$criteria = array('id' => $berkas);
				$inbox = $this -> ci -> em -> getRepository('\models\entities\Inbox') -> findOneBy($criteria);

				$inboxService = new InboxService;
				$cond = "OK";
				$criteria = array('origin' => $inbox->getProcedureStep());
				$ps = $this->ci->em->getRepository('\models\entities\ProcedureTransition')->findOneBy($criteria);
			
				if ($ps->getCondition() == "FINISH"){
					$cond = "FINISH";
					$berkas->setApprover($user->getUserId());	
				} 

				$this -> ci -> em -> persist($berkas);
				$this -> ci -> em -> flush();
				
				if ($inboxService -> nextInboxStep($inbox, $profile, $cond) === FALSE) {
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}

				// insert new berkasComment
				$berkasText = $this -> ci -> input -> post('BerkasComment_text');
				if ($berkasText != '') {
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment -> setBerkas($berkas);
					$procedureStepId = $this -> ci -> input -> post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this -> ci -> em -> getRepository('\models\entities\ProcedureStep') -> findOneBy($criteria);
					$berkasComment -> setProcedureStep($ps);
					//$user = \models\service\CurrentUser::user();
					$berkasComment -> setSender($user -> getUserId());
					$berkasComment -> setText($berkasText);
					$this -> ci -> em -> persist($berkasComment);
					$this -> ci -> em -> flush();
				}

				$criteria = array('berkas' => $berkas);
				$berkasAttachments = $this -> ci -> em -> getRepository('\models\entities\BerkasAttachment') -> findBy($criteria);
				if (count($berkasAttachments) > 0) {
					$c = 1;
					foreach ($berkasAttachments as $berkasAttachment) {
						$index = 'attach' . $c;
						//echo $index;
						if ($_FILES[$index]['error'] == 0) {
							$this -> deleteBerkasAttachment($berkasAttachment -> getId());
						}
						$c++;
					}

					//throw new \Exception("GAGAL UPLOAD DOC");
					if ($this -> insertBerkasAttachment($berkas, $_FILES) === FALSE) {
						throw new \Exception("GAGAL UPLOAD DOC");
					}
				} else {
					if ($this -> insertBerkasAttachment($berkas, $_FILES) === FALSE) {
						throw new \Exception("GAGAL UPLOAD DOC");
					}
				}
				
				if ($cond == "FINISH"){
					$notifService = new NotificationService;
					$notifService -> sendMail($berkas->getId());	
				}

				/*	if ($this->isNewUploadFile($_FILES) === TRUE){
				 $criteria = array('berkas' => $berkas);
				 $berkasAttachments = $this->ci->em->getRepository('\models\entities\BerkasAttachment')->findBy($criteria);
				 if (count($berkasAttachments) > 0){
				 foreach ($berkasAttachments as $berkasAttachment){
				 $this->deleteBerkasAttachment($berkasAttachment->getId());
				 }
				 }
				 if ($this->insertBerkasAttachment($berkas, $_FILES) ===FALSE){
				 throw new \Exception("GAGAL UPLOAD DOC");
				 }
				 }  */

				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				echo $e -> getMessage();
				//die("kmp");
				return FALSE;
			}

			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function submitBerkas($berkas, $profileId) {
		if ($berkas != NULL) {
			$user = \models\service\CurrentUser::user();
			$this -> ci -> em -> getConnection() -> beginTransaction();
			// suspend auto-commit
			try {
				$criteria = array('id' => $profileId);
				$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);

				$criteria = array('id' => $berkas -> getId());
				$inbox = $this -> ci -> em -> getRepository('\models\entities\Inbox') -> findOneBy($criteria);

				$inboxService = new InboxService;
				$cond = 'OK';
				if ($inbox -> getProcedureStep() -> getId() == 3) {
					$cond = 'FINISH';
					$berkas -> setApprover($user -> getUserId());
					$berkas -> setEndDate(new \DateTime('now', new \DateTimeZone("Asia/Jakarta")));
				} else if ($inbox -> getProcedureStep() -> getId() == 2) {
					$berkas -> setVerifier($user -> getUserId());
				}
				$berkas -> setResult($cond);

				$this -> ci -> em -> persist($berkas);
				$this -> ci -> em -> flush();

				if ($inboxService -> nextInboxStep($inbox, $profile, $cond) === FALSE) {
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}

				// update berkas

				// insert new berkasComment
				$berkasText = $this -> ci -> input -> post('BerkasComment_text');
				if ($berkasText != '') {
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment -> setBerkas($berkas);
					$procedureStepId = $this -> ci -> input -> post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this -> ci -> em -> getRepository('\models\entities\ProcedureStep') -> findOneBy($criteria);
					$berkasComment -> setProcedureStep($ps);
					$user = \models\service\CurrentUser::user();
					$berkasComment -> setSender($user -> getUserId());
					$berkasComment -> setText($berkasText);
					$this -> ci -> em -> persist($berkasComment);
					$this -> ci -> em -> flush();
				}

				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				echo $e -> getMessage();

				return FALSE;
			}

			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function submitBerkasForVerAndApp($berkas, $profileId, $cond = "OK") {
		if ($berkas != NULL) {
			$berkasId = $berkas->getId();
			$this -> ci -> em -> getConnection() -> beginTransaction();
			// suspend auto-commit
			try {
				if ($cond == "OK" || $cond == "NOK" || $cond == "FINISH") {
					$this -> ci -> em -> persist($berkas);
					$this -> ci -> em -> flush();

					// insert new berkasComment
					$berkasText = $this -> ci -> input -> post('BerkasComment_text');
					if ($berkasText != '') {
						$berkasComment = new \models\entities\BerkasComment;
						$berkasComment -> setBerkas($berkas);
						$procedureStepId = $this -> ci -> input -> post('ProcedureStep_id');
						$criteria = array('id' => $procedureStepId);
						$ps = $this -> ci -> em -> getRepository('\models\entities\ProcedureStep') -> findOneBy($criteria);
						$berkasComment -> setProcedureStep($ps);
						$user = \models\service\CurrentUser::user();
						$berkasComment -> setSender($user -> getUserId());
						$berkasComment -> setText($berkasText);
						$this -> ci -> em -> persist($berkasComment);
						$this -> ci -> em -> flush();
					}
				}

				if ($cond == "CANCEL") {
					$berkas -> setResult("CANCEL");
					$this -> ci -> em -> persist($berkas);
					$this -> ci -> em -> flush();
				}

				$criteria = array('id' => $profileId);
				$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);

				$criteria = array('id' => $berkas -> getId());
				$inbox = $this -> ci -> em -> getRepository('\models\entities\Inbox') -> findOneBy($criteria);

				$inboxService = new InboxService;
				if ($inboxService -> nextInboxStep($inbox, $profile, $cond) === FALSE) {
					throw new \Exception("GAGAL NEXT INBOX STEP");
				}
				//echo $berkasId;
				if ($cond == "FINISH"){
					$notifService = new NotificationService;
					$notifService -> sendMail($berkasId);	
				//	throw new \Exception($berkasId);
				} else if ($cond=="NOK" && ($profileId == 7 || $profileId == 8)) {
					$notifService = new NotificationService;
					$notifService -> sendMail($berkasId,"NOK");
					//throw new \Exception($berkasId);
				} 
				
				//throw new \Exception("MAINTENANCE");
				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				echo $e -> getMessage();

				return FALSE;
			}
			//die();
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function deleteMemberOfTraining($id) {
		if ($id > 0) {
			$criteria = array('id' => $id);
			$item = $this -> ci -> em -> getRepository('\models\entities\ParticipantOfTraining') -> findOneBy($criteria);
			$this -> ci -> em -> remove($item);
			$this -> ci -> em -> flush();

			return TRUE;
		}

		return FALSE;
	}

	public function deleteBerkasAttachment($id) {
		if ($id > 0) {
			$criteria = array('id' => $id);
			$item = $this -> ci -> em -> getRepository('\models\entities\BerkasAttachment') -> findOneBy($criteria);
			$this -> ci -> em -> remove($item);
			$this -> ci -> em -> flush();

			return TRUE;
		}

		return FALSE;
	}

	public function submitReview($berkas, $profileId, $cond = "OK") {
		if ($berkas != NULL) {
			$this -> ci -> em -> getConnection() -> beginTransaction();
			// suspend auto-commit
			try {
				$this -> ci -> em -> persist($berkas);
				$this -> ci -> em -> flush();
				$user = \models\service\CurrentUser::user();
				// insert new berkasComment
				$berkasText = $this -> ci -> input -> post('BerkasComment_text');
				if ($berkasText != '') {
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment -> setBerkas($berkas);
					$procedureStepId = $this -> ci -> input -> post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this -> ci -> em -> getRepository('\models\entities\ProcedureStep') -> findOneBy($criteria);
					$berkasComment -> setProcedureStep($ps);

					$berkasComment -> setSender($user -> getUserId());
					$berkasComment -> setText($berkasText);
					$this -> ci -> em -> persist($berkasComment);
					$this -> ci -> em -> flush();
				}

				$criteria = array('id' => $profileId);
				$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);

				$criteria = array('id' => $berkas -> getId());
				$inbox = $this -> ci -> em -> getRepository('\models\entities\Inbox') -> findOneBy($criteria);

				/*$criteria = array('userId' => $user);
				 $userVerifikator = $this->ci->em->getRepository('\models\entities\UserVerifikator')->findBy($criteria);
				 if ($userVerifikator[0]->getJenisVerifikator()->getId()==2){
				 $inbox->setJumlahVerify(1);
				 $inbox->setLastVer($user->getUserId());
				 $this->ci->em->persist($inbox);
				 $this->ci->em->flush();
				 }*/
				if ($inbox -> getProcedureStep() -> getVerifyByJumlah() != NULL && $inbox -> getProcedureStep() -> getVerifyByJumlah() > 0) {
					$jmlh = $inbox -> getJumlahVerify();
					if ($jmlh == NULL) {
						$jmlh = 0;
					}
					$inbox -> setJumlahVerify($jmlh + 1);
					$inbox -> setLastVer($user -> getUserId());
					$this -> ci -> em -> persist($inbox);
					$this -> ci -> em -> flush();
				}

				$berkasActivity = new \models\entities\BerkasActivity;
				$berkasActivity -> setBerkas($berkas);
				$berkasActivity -> setProcedureStep($inbox -> getProcedureStep());
				$berkasActivity -> setProfile($profile);
				$berkasActivity -> setAction("REVIEW");
				/*if ($profileId == 9){
				 $berkasActivity->setAction("APPROVED");
				 } else {
				 $berkasActivity->setAction("REVIEW");
				 }*/

				$user = CurrentUser::user();
				$berkasActivity -> setUser($user -> getUserId());

				$this -> ci -> em -> persist($berkasActivity);
				$this -> ci -> em -> flush();

				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				echo $e -> getMessage();

				return FALSE;
			}

			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function submitFirstApprove($berkas, $profileId, $cond = "OK") {
		if ($berkas != NULL) {
			$this -> ci -> em -> getConnection() -> beginTransaction();
			// suspend auto-commit
			try {
				$this -> ci -> em -> persist($berkas);
				$this -> ci -> em -> flush();
				$user = \models\service\CurrentUser::user();
				// insert new berkasComment
				$berkasText = $this -> ci -> input -> post('BerkasComment_text');
				if ($berkasText != '') {
					$berkasComment = new \models\entities\BerkasComment;
					$berkasComment -> setBerkas($berkas);
					$procedureStepId = $this -> ci -> input -> post('ProcedureStep_id');
					$criteria = array('id' => $procedureStepId);
					$ps = $this -> ci -> em -> getRepository('\models\entities\ProcedureStep') -> findOneBy($criteria);
					$berkasComment -> setProcedureStep($ps);

					$berkasComment -> setSender($user -> getUserId());
					$berkasComment -> setText($berkasText);
					$this -> ci -> em -> persist($berkasComment);
					$this -> ci -> em -> flush();
				}

				$criteria = array('id' => $profileId);
				$profile = $this -> ci -> em -> getRepository('\models\entities\Profile') -> findOneBy($criteria);

				$criteria = array('id' => $berkas);
				$inbox = $this -> ci -> em -> getRepository('\models\entities\Inbox') -> findOneBy($criteria);

				$criteria = array('userId' => $user);
				$userVerifikator = $this -> ci -> em -> getRepository('\models\entities\UserVerifikator') -> findBy($criteria);

				if ($inbox -> getJumlahApprover() == null || $inbox -> getJumlahApprover() < 1) {
					$inbox -> setJumlahApprover(1);
					$inbox -> setLastApp($user -> getUserId());
					$this -> ci -> em -> persist($inbox);
					$this -> ci -> em -> flush();
				}

				$berkasActivity = new \models\entities\BerkasActivity;
				$berkasActivity -> setBerkas($berkas);
				$berkasActivity -> setProcedureStep($inbox -> getProcedureStep());
				$berkasActivity -> setProfile($profile);
				$berkasActivity -> setAction("FIRST APPROVE");
				$user = CurrentUser::user();
				$berkasActivity -> setUser($user -> getUserId());

				$this -> ci -> em -> persist($berkasActivity);
				$this -> ci -> em -> flush();

				$this -> ci -> em -> getConnection() -> commit();
				$this -> lastBerkas = $berkas;

			} catch (\Exception $e) {
				$this -> ci -> em -> getConnection() -> rollback();
				$this -> ci -> em -> close();
				echo $e -> getMessage();

				return FALSE;
			}

			return TRUE;
		} else {
			return FALSE;
		}
	}

	function isNewUploadFile($files) {
		$isNewFile = FALSE;

		if ($files['attach1']['error'] == 0 || $files['attach2']['error'] == 0 || $files['attach3']['error'] == 0 || $files['attach4']['error'] == 0 || $files['attach5']['error'] == 0) {
			$isNewFile = TRUE;
		}

		return $isNewFile;
	}

}
